import OpenAI from "openai";
import common from '../../lib/common/common.js'

//本插件是根据<https://github.com/NotIvny/Yunzai-DeepSeek-JS>改写而来，感谢大佬！

let groupChatHistories = new Map()
const CURRENT_MODEL = '<自行填写模型名称>'
const openai = new OpenAI({
    baseURL: '<自行填写URL>',
    apiKey: '<自行填写sk>'
});

let processingGroups = new Map();

export class DeepSeek extends plugin {
    constructor() {
        super({
            name: 'deepseek',
            dsc: '深度求索AI对话插件',
            event: 'message',
            priority: -2000,
            rule: [{
                    reg: '^#ds([\\s\\S]*)$',
                    fnc: 'handleChat'
                },
                {
                    reg: '^#结束对话$',
                    fnc: 'resetChatHistory'
                },
                {
                    reg: '^#ai设置上下文长度(.*)$',
                    fnc: 'setContextLength',
                    permission: 'master'
                },
                {
                    reg: '^#ai设置温度(.*)$',
                    fnc: 'setTemperature',
                    permission: 'master'
                },
                {
                    reg: '^#ai设置思考过程(.*)$',
                    fnc: 'setThinkingProcess',
                    permission: 'master'
                }
            ]
        })
    }

    async handleChat(e) {
        if (processingGroups.get(e.group_id)) {
            return e.reply('少女正在思考中，请稍后再试~')
        }

        const maxContextLength = Math.min(Math.max(parseInt(await redis.get('deepseekJS:maxLength')) || 3, 0), 10)
        const temperature = Math.min(Math.max(parseFloat(await redis.get('deepseekJS:temperature')) || 1, 0), 2)

        const userMessage = e.msg.replace('#ds', '').trim()
        if (!userMessage) return e.reply('请输入有效内容')

        let history = groupChatHistories.get(e.group_id) || []

        if (maxContextLength > 0) {
            if (history.length > 2 * maxContextLength) {
                history = history.slice(-2 * maxContextLength)
            }
        } else {
            history = []
        }

        const systemPrompt = {
            role: "system",
            content: `
1. 使用口语化的简体中文回答
2. 尽量不使用emoji表情
3. 回答不必太拘谨，但如涉及过于敏感的内容，请礼貌拒绝
4. 用户的提问和要求请尽量满足
`
        }

        const chatContext = [
            systemPrompt,
            ...history,
            {
                role: "user",
                content: `[用户 ${e.sender.nickname}(UserID: ${e.user_id})]：${userMessage}`
            }
        ]

        processingGroups.set(e.group_id, true)
        await this.processChatRequest(e, chatContext, temperature)
    }

    async resetChatHistory(e) {
        groupChatHistories.delete(e.group_id)
        e.reply('对话历史已重置')
    }

    async processChatRequest(e, context, temperature) {
        const startTime = Date.now()

        try {
            await e.reply('少女思考中~', 1)

            const completion = await openai.chat.completions.create({
                messages: context,
                model: CURRENT_MODEL,
                temperature: temperature,
                frequency_penalty: 0.2,
                presence_penalty: 0.2,
            })

            const processingTime = Date.now() - startTime
            const rawResponse = completion.choices[0].message.content
            const thinkingProcess = completion.choices[0].message.reasoning_content
            const showThinking = await redis.get('deepseekJS:forwardMsg') || 0

            const cleanedResponse = this.cleanResponse(rawResponse)
            const replyContent = [
                `${cleanedResponse}`,
                `⏱️ 响应耗时：${processingTime}ms`
            ]
            const forwardMsg = await common.makeForwardMsg(e, replyContent)
            await e.reply(forwardMsg)

            if (thinkingProcess && showThinking == 1) {
                const thinkingMsg = await common.makeForwardMsg(e, [
                    'DeepSeek思考过程：',
                    `${thinkingProcess}`
                ])
                await e.reply(thinkingMsg)
            }

            const updatedHistory = [
                ...context.slice(1),
                {
                    role: 'assistant',
                    content: rawResponse
                }
            ]
            groupChatHistories.set(e.group_id, updatedHistory)

        } catch (error) {
            logger.error('API请求失败:', error)
            const errorCode = error.status || 'UNKNOWN'
            const errorMsg = error.message?.substring(0, 50) || '未知错误'
            e.reply([
                `请求失败（错误码：${errorCode}）`,
                `错误信息：${errorMsg}...`,
            ].join('\n'), true)
        } finally {
            processingGroups.set(e.group_id, false)
        }
    }

    cleanResponse(rawMessage) {
        return rawMessage
            .trim()
            .replace(/\n{3,}/g, '\n\n')
    }

    async setContextLength(e) {
        const length = Math.min(Math.max(parseInt(e.msg.replace(/#ai设置上下文长度/, '')) || 0, 0), 10)
        await redis.set('deepseekJS:maxLength', length)
        e.reply(length === 0 ? '🗑️ 上下文功能已关闭' : `📦 上下文长度已设置为：${length}轮对话`)
    }

    async setTemperature(e) {
        const tempValue = Math.min(Math.max(parseFloat(e.msg.replace(/#ai设置温度/, '')) || 1.0, 0), 2)
        await redis.set('deepseekJS:temperature', tempValue)
        e.reply(`🌡️ 温度系数已设置为：${tempValue.toFixed(1)}`)
    }

    async setThinkingProcess(e) {
        const arg = e.msg.replace(/#ai设置思考过程/, '').trim()
        const statusMapping = {
            '关闭': 0,
            '开启': 1
        }

        if (statusMapping.hasOwnProperty(arg)) {
            await redis.set('deepseekJS:forwardMsg', statusMapping[arg])
            e.reply(statusMapping[arg] ? '💡 已开启思考过程显示' : '🕶️ 已关闭思考过程显示')
        } else {
            e.reply('参数错误，可选值：\n关闭 - 不显示思考过程\n开启 - 显示完整思考过程')
        }
    }
}